package avicit.bdp.dms.dss.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.common.utils.EntityUtils;
import avicit.bdp.core.constant.Constants;
import avicit.bdp.dms.dss.dao.DssUserDAO;
import avicit.bdp.dms.dss.dto.DssUserDTO;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.properties.PlatformConstant;
import avicit.platform6.core.rest.msg.QueryRespBean;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 数据资源用户表服务
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class DssUserService extends BaseService<DssUserDAO, DssUserDTO> {

    public static final Integer DEFAULT_DAY_COUNT = 1000;

    public QueryRespBean<DssUserDTO> findUserList(String keyWords, Integer pageNo, Integer pageSize) {
        QueryRespBean<DssUserDTO> queryRespBean = new QueryRespBean<>();
        try {
            PageHelper.startPage(pageNo, pageSize);
            Page<DssUserDTO> dataList = this.mapper.findUserList(keyWords);
            queryRespBean.setResult(dataList);
            BdpLogUtil.log4Query(queryRespBean);
            return queryRespBean;
        } catch (Exception e) {
            throw new BusinessException(e.getMessage(), e);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void insertUser(String userIds, String userNames) {
        if (StringUtils.isAnyBlank(userIds, userNames)) {
            throw new BusinessException("请检查参数!");
        }
        String[] idArray = userIds.split(Constants.COMMA);
        String[] nameArry = userNames.split(Constants.COMMA);
        if(idArray.length!=nameArry.length){
            throw new BusinessException("请检查参数!是否有脏数据!");
        }
        for (int i=0;i<idArray.length;i++) {
            boolean flag = validateUserId(idArray[i]);
            if(flag) {
                DssUserDTO dssUserDTO = new DssUserDTO();
                dssUserDTO.setId(ComUtil.getId());
                dssUserDTO.setToken(ComUtil.getId());
                dssUserDTO.setDayCount(DEFAULT_DAY_COUNT);
                dssUserDTO.setValidDate(null);
                dssUserDTO.setUserId(idArray[i]);
                dssUserDTO.setUserName(nameArry[i]);
                EntityUtils.setCreateAndUpdateInfo(dssUserDTO);
                this.mapper.insert(dssUserDTO);
                //记录日志
                BdpLogUtil.log4Insert(dssUserDTO);
            }
        }
    }

    private boolean validateUserId(String userId) {
        DssUserDTO query = new DssUserDTO();
        query.setUserId(userId);
        DssUserDTO dssUserDTO = this.selectOne(query);
        return dssUserDTO == null;
    }


    @Transactional(rollbackFor = Exception.class)
    public void updateUser(DssUserDTO dssUser) {
        try {
            updateByPrimaryKey(getDataElement(dssUser));
        } catch (Exception e) {
            throw new BusinessException(e.getMessage(), e);
        }
    }

    private DssUserDTO getDataElement(DssUserDTO dssUser) throws ParseException {
        DssUserDTO oldDTO = selectByPrimaryKey(dssUser.getId());
        if (oldDTO == null) {
            throw new BusinessException("数据不存在");
        }
        //记录日志
        BdpLogUtil.log4Update(dssUser, oldDTO);

        oldDTO.setToken(dssUser.getToken());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if(dssUser.getValidDateStr()!=null) {
            Date date = simpleDateFormat.parse(dssUser.getValidDateStr());
            oldDTO.setValidDate(date);
        }else {
            oldDTO.setValidDate(null);
        }
        oldDTO.setDayCount(dssUser.getDayCount());
        return oldDTO;
    }


    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new BusinessException("删除失败！传入的参数主键为null");
        }
        try {
            //记录日志
            DssUserDTO project = selectByPrimaryKey(id);
            if (project == null) {
                throw new BusinessException("删除失败！对象不存在");
            }
            BdpLogUtil.log4Delete(project);
            //删除业务数据
            deleteByPrimaryKey(id);
        } catch (Exception e) {
            throw new BusinessException(e.getMessage(), e);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public String updateToken(String id) {
        try {
            String token = ComUtil.getId();
            DssUserDTO dssUserDTO = this.selectByPrimaryKey(id);
            dssUserDTO.setToken(token);
            this.updateByPrimaryKeySelective(dssUserDTO);
            String logTitle = "更新token";
            BdpLogUtil.log("用户详情模块",logTitle, PlatformConstant.OpType.update);
            return token;
        } catch (Exception e) {
            throw new BusinessException(e.getMessage(), e);
        }
    }

    public DssUserDTO findUserByUserId() {
        String userId = ThreadContextHelper.getUserId();
        DssUserDTO dssUserDTO = new DssUserDTO();
        dssUserDTO.setUserId(userId);
        DssUserDTO user = this.selectOne(dssUserDTO);
        if( user == null){
            dssUserDTO.setId(ComUtil.getId());
            dssUserDTO.setToken(ComUtil.getId());
            dssUserDTO.setDayCount(DEFAULT_DAY_COUNT);
            dssUserDTO.setValidDate(null);
            dssUserDTO.setUserName(ThreadContextHelper.getUserName());
            this.mapper.insert(dssUserDTO);
            BdpLogUtil.log4Query(dssUserDTO);
            return dssUserDTO;
        }
        BdpLogUtil.log4Query(user);
        return user;
    }

}
